# -*- coding: utf-8 -*-
# @Author  : pony.guan
# @Time    : 2021/12/2 10:33
# Description:
import json

import requests

"""
iwms stations: XSYS100~XSYS107
"""


# 1. 人工创建工期规格(一般都有现成的)、创建iwms工作站、人工iwms播种墙（绑定创建的iwms工作站） 工作站为:XSYS100~XSYS110
# 1.1　接口创建iwms工作站


def create_iwms_station(iwms_stations):
    ip = '47.106.68.206'
    port = '7301'
    create_station_url = f'http://{ip}:{port}/station/createStationThroughESS'

    for iwms_station in iwms_stations:
        params = {
            'stationCode': iwms_station,
            'stationOperationType': 'OUTBOUND',
            'stationPhysicalType': 'ROBOT',
            'useEssData': 'false'
        }

        print('开始创建iwms工作站:', iwms_station)
        r = requests.get(url=create_station_url, params=params)

        assert r.json()['code'] in [0, '0']
        print('创建iwms工作站:', iwms_station, '成功')


# 1.2  人工iwms播种墙（绑定创建的iwms工作站）


# 2. ess创建同名工作站并与iwms中形成映射
#


# 2.1 地图中找出边界上水平的且不处于交叉位置的点位


# 2.2 添加取放货点 & 创建ess工作站管理iwms中的工作站
def create_ess_station_mapping(points, iwms_stations):
    ip = '47.106.68.206'
    port = '9000'
    url = f'http://{ip}:{port}/model/updateModelNotSafe'
    headers = {
        "Content-Type": "application/json",
    }
    for point, station_code in zip(points, iwms_stations):
        x, y = point
        code = f"LT_LABOR:POINT:{x}:{y}"
        point_code = f"POINT:{x}:{y}"
        data = {
            "id": "1711248363040541696",
            "code": code,
            "updated": "1631973612824",
            "location": {
                "id": "1711248363040541696",
                "code": code,
                "locationTypeCode": "LT_LABOR",
                "position": {
                    "x": f"{x}",
                    "y": f"{y}",
                    "z": "0"
                },
                "link": [
                    {
                        "pointCode": point_code,
                        "robot2mapTheta": "0",
                        "container2mapTheta": "0"
                    }
                ],
                "isLocked": False,
                "isAbnormal": False,
                "abnormalReason": "NONE",
                "storageTag": "",
                "containerCode": "",
                "actionFailedCount": {}
            }
        }
        print('开始创建取放货点:', point)
        r = requests.post(url=url, data=json.dumps(data), headers=headers)

        assert r.json()['code'] in [0, '0']
        print('创建取放货点:', point, '成功')

        data1 = {
            "id": "1711248438992048640",
            "code": station_code,
            "updated": "1631974502789",
            "additionData": {
                "info": ""
            },
            "locationActor": {
                "id": "1711248438992048640",
                "code": station_code,
                "boundLocation": {
                    code: True
                },
                "boxType": "GREY_BOX",
                "putawayByTask": False,
                "isScanBeforeLoad": False,
                "isRdkConveyorMode": False,
                "canSwitchInOrOut": False,
                "locationCodeToBack": {},
                "groupOwner": {
                    "group1": "MAN"
                },
                "group": {
                    "group1": {
                        "locationCode": []
                    }
                },
                "nonWorkingLocation": [],
                "highestTierWhenOutbound": 0,
                "highestTierWhenInbound": 0,
                "tryActionRule": {
                    "ignoreAllChecks": False,
                    "ignoreCheckContainer": False,
                    "containerNeedTheSameForLoad": False,
                    "needContainerForLoad": False,
                    "locationNeedEmptyForUnload": False,
                    "unloadBlockedHandling": "TASK_AWAITING",
                    "checkGroupOwner": False,
                    "unloadNeedToConfirm": False,
                    "unloadConfirmValidTimeMs": "0",
                    "forkHitDetectionAction": [],
                    "forkHitDetectionSafetyDistance": "0",
                    "robotActionDistanceErrorRange": "0"
                },
                "endActionRule": {
                    "defaultFailedHandling": "TASK_SUSPEND_ROBOT_AWAITING",
                    "scanFailedHandling": "TASK_SUSPEND_ROBOT_AWAITING",
                    "loadFailedHandling": "TASK_SUSPEND_ROBOT_AWAITING",
                    "unloadFailedHandling": "TASK_SUSPEND_ROBOT_AWAITING",
                    "manualFailedHandling": "TASK_SUSPEND_ROBOT_AWAITING",
                    "ignoreScanResult": False,
                    "scanResultCorrectionData": False,
                    "locationAbnormalLoadFailedCount": 0,
                    "isOutsideAsRobotUnload": False,
                    "prepareAction": False,
                    "leaveAsNoTask": False,
                    "forceCheckTaskOfPutawayAfterScan": False,
                    "locationAbnormalAfterScanFailed": False
                },
                "callRobotRule": {
                    "allowedCallRobot": True,
                    "defaultCallRobotLocation": [],
                    "callRobotAfterLoadLocation": [],
                    "totalCallRobotLimit": 0,
                    "callRobotLimitPerLocation": 0,
                    "onlyInbound": False
                },
                "nonRobotActionRule": {
                    "isAllowedNonRobotLoad": True,
                    "isAllowedNonRobotUnload": True,
                    "isInsideAsNonRobotLoad": True,
                    "isOutsideAsNonRobotUnload": True,
                    "isAllowedNotSpecifyingContainer": True,
                    "overwrittenLocationAsNonRobotLoad": []
                },
                "kubotLabor": True
            }
        }

        r1 = requests.post(url=url, data=json.dumps(data1), headers=headers)

        print('开始添加人工工作站&映射:', '点位:', point, '两边的station_code均为:', station_code)
        assert r1.json()['code'] in [0, '0']
        print('添加人工工作站&映射成功:', point, '成功', )


# 3.重启服务
# 　　　　重启actor
#       restartController
#       oneClickCreateMockKubot
#       系统恢复

"""

"""


# tagId: 100-3   100-1
# code: XSYS100
# stationCode: XSYS100


# tagId 100-4   100-2
# code: XSYS100
# stationCode: XSYS100


def create_put_wall(iwms_stations):
    ip = '47.106.68.206'
    port = '9001'
    create_put_wall_url = f'http://{ip}:{port}/gw/station/putWall/createOrUpdatePutWall'
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Mzg5NzkxMTgsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiKjoqIiwiJCQkJiYmISEhUk9MRV9zdXBlcl9hZG1pbiJdLCJqdGkiOiJiNDk2NjMzMy1mZGY4LTQzMzEtOWU3MS1iYTA2ZWU3ZTlhNTYiLCJjbGllbnRfaWQiOiJhZG1pbl9jbGllbnQiLCJzY29wZSI6WyJhbGwiXX0.jXf1D8ve7gLtpfbngcJf2Sn3ldkpE1FPjA7bv9KUqEo"
    }
    for station_code in iwms_stations:
        code = station_code
        tag_ids = [station_code[4:] + f'-{i}' for i in [3, 1, 4, 2]]

        data = [{"containerSpecCode": "4槽位播种墙", "containerSpecType": "STATION_STATIC_PUTWALL", "description": "4槽位播种墙",
                 "containerSpecStatus": "ENABLE", "level": 2, "bay": 1, "length": 0, "width": 0, "height": 0,
                 "volume": 0,
                 "subContainerNum": 2, "subContainerList": [
                {"subContainerCode": "LA1", "subContainerLevel": 1, "subContainerBay": 1,
                 "subContainerStatus": "ENABLE",
                 "putWallSlotCode": "LA1", "isSinglePutWallSlot": "FALSE", "ksStationTaskRuleId": "651025278772596736",
                 "tagId": tag_ids[0], "priority": 2, "location": "LEFT"},
                {"subContainerCode": "LB1", "subContainerLevel": 2, "subContainerBay": 1,
                 "subContainerStatus": "ENABLE",
                 "putWallSlotCode": "LB1", "isSinglePutWallSlot": "FALSE", "ksStationTaskRuleId": "651025278772596736",
                 "tagId": tag_ids[1], "priority": 1, "location": "LEFT"}], "location": "LEFT", "essContainerType": "",
                 "putWallDisplayStyle": "MERGE", "kind": "STATION_STATIC_PUTWALL",
                 "ksStationTaskRuleId": "651025278772596736",
                 "code": code, "stationCode": station_code, "putWallStatus": "ENABLE"},
                {"containerSpecCode": "4槽位播种墙", "containerSpecType": "STATION_STATIC_PUTWALL", "description": "4槽位播种墙",
                 "containerSpecStatus": "ENABLE", "level": 2, "bay": 1, "length": 0, "width": 0, "height": 0,
                 "volume": 0,
                 "subContainerNum": 2, "subContainerList": [
                    {"subContainerCode": "RA1", "subContainerLevel": 1, "subContainerBay": 1,
                     "subContainerStatus": "ENABLE",
                     "putWallSlotCode": "RA1", "isSinglePutWallSlot": "FALSE",
                     "ksStationTaskRuleId": "651025278772596736",
                     "tagId": tag_ids[2], "priority": 1, "location": "RIGHT"},
                    {"subContainerCode": "RB1", "subContainerLevel": 2, "subContainerBay": 1,
                     "subContainerStatus": "ENABLE",
                     "putWallSlotCode": "RB1", "isSinglePutWallSlot": "FALSE",
                     "ksStationTaskRuleId": "651025278772596736",
                     "tagId": tag_ids[3], "priority": 2, "location": "RIGHT"}], "location": "RIGHT",
                 "essContainerType": "",
                 "putWallDisplayStyle": "MERGE", "kind": "STATION_STATIC_PUTWALL",
                 "ksStationTaskRuleId": "651025278772596736",
                 "code": code, "stationCode": station_code, "putWallStatus": "ENABLE"}]

        print('开始创建播种墙:', code)
        r = requests.post(url=create_put_wall_url, data=json.dumps(data), headers=headers)
        assert r.json()['code'] in [0, '0']
        print('创建播种墙成功:', code, '成功', )


if __name__ == '__main__':
    iwms_stations = [f'XSYS{i}' for i in range(100, 111)]

    # todo: 1. 目前，下的一个一个调，2.且存在容规：4槽位播种墙　　3. 创建播种墙需获最新token　
    # 1.1 创建iwms工作站
    # create_iwms_station(iwms_stations)
    # 1.2. 创建播种墙
    # create_put_wall(iwms_stations)
    # 2. ess创建工作站&mapping
    # 已经被占用的点位： 86650:94330
    points = [
        (3500, 92790),
        (5900, 92790),
        (13080, 92790),
        (16230, 94330),
        (28360, 94330),
        (31650, 94330),
        (42780, 94330),
        (55650, 94330),
        (69920, 94330),
        (82190, 94330),
        (86650, 94330),
    ]
    # create_ess_station_mapping(points, iwms_stations)

    # 3. 重启服务
    # 　　　　重启actor: restartController
    #       restartController
    #       oneClickCreateMockKubot
    #       点接系统恢复